package com.yenroc.ho.netty;

import com.yenroc.ho.netty.enums.GlobalTransactionType;
import com.yenroc.ho.transaction.GlobalTransactionInfo;
import com.yenroc.ho.transaction.GlobalTransactionManager;
import io.netty.channel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


/**
 * @author： heyanpeng
 * @date： 2021/7/27
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private final Logger log = LoggerFactory.getLogger(NettyClientHandler.class);


    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("NettyClientHandler 发生异常", cause);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        log.info("接收数据===" + obj);
        TkMessageVo msg = (TkMessageVo) obj;

        List<GlobalTransactionInfo> transactionInfos = GlobalTransactionManager.getTransactionInfo(msg.getGroupId());
        if (transactionInfos == null || transactionInfos.size() == 0) {
            return;
        }
        for (GlobalTransactionInfo transactionInfo : transactionInfos) {
            if (msg.getTransactionId().equals(transactionInfo.getTransactionId())) {
                if (GlobalTransactionType.commit == msg.getTransactionType()) {
                    transactionInfo.setType(GlobalTransactionType.commit);
                } else if (GlobalTransactionType.rollback == msg.getTransactionType()) {
                    transactionInfo.setType(GlobalTransactionType.rollback);
                }
                log.info("唤醒事务=[{}]..", transactionInfo.getTransactionId());
                transactionInfo.getTask().signalTask();
                log.info("全局事务【{}】处理完成,本地事务=【{}】，执行【{}】===", transactionInfo.getGroupId(),transactionInfo.getTransactionId(), transactionInfo.getType());
            }
        }
    }

}
